import json
import os

import xlrd
import xmltodict, dicttoxml
import xml.dom.minidom
import json

"""
webservice转换相关
"""


#body中header转XML
def json_to_xml(Content_Type_header):
    # xmltodict库的unparse()json转xml
    # 参数pretty 是格式化xml
    print("进来了！！！！！！！！！！！！！！！！！！！")
    print(Content_Type_header)
    print(type(Content_Type_header))  #dict

    xml_str = xmltodict.unparse(Content_Type_header)
    xmlHead = "".join(xml_str.split())
    print(xmlHead)

    """删除不用的xml，得到替换的xmlhead"""
    xmlHead = xmlHead.replace('<?xmlversion="1.0"encoding="utf-8"?><reqHeadDemo>', '')
    THxmlHead = xmlHead.replace('</reqHeadDemo>', '')  # 替换xmlHead准备
    return THxmlHead

#body中body转XML
def xmlDataBuild(caseData,ListData):

    print(caseData)
    print("A")
    print(ListData)
    print("B")
    xmlListName = ListData['apiListPadding']
    print("C")
    print(xmlListName)



    maxLen = 0
    listA = []

    list1 = []
    print("D")
    for key in caseData:  # 获取最大长度

        list = caseData[key]['param_value'].split(",")

        len_list = caseData[key]['param_value']
        json1 = {}
        print("E")

        if len(list) > maxLen:  # 循环判断list长度是否统一
            maxLen = len(list)

        elif (len(list) == maxLen):
            maxLen = maxLen

        else:
            print("有问题")

    j = 0
    listA = []
    print("F")

    while (j < len(list)):
        listA.append("##")
        print("G")

        for key in caseData:  # 获取最大长度
            jsonA = {}

            list = caseData[key]['param_value'].split(",")

            jsonA[(caseData[key]['param_key'])] = list[j]

            listA.append(jsonA)
        j = j + 1
    print("G11111")

    strListA = str(listA)
    strListA = strListA.replace('}, {', ',')  # 取出不必要的括号
    strListA = strListA.replace("['##',", "[")  # 去除lit最前面的##,
    strListA = strListA.replace("''", "")  # 去除lit最前面的##,
    strListA = strListA.replace("'##',", "")  # 去除lit最前面的##,
    print("HHHH")
    print(strListA)


    result = json.dumps(eval(strListA))
    print("000")
    result = '{"' + xmlListName + '":' + result + '}'
    print(11111)
    result = '{"LIST":' + result + '}'
    print(22222)
    print("result")

    result = (eval(result))
    print("H")
    print(result)
    data_xml = dicttoxml.dicttoxml(result)

    data_xml = data_xml.decode("utf-8")

    data_xml = data_xml.replace('"', "'")
    """结果1"""
    print(data_xml)

    import xml.dom.minidom

    """去除生成的xml文件的type类型、xml头、root标签"""

    result2 = data_xml.replace("<item type='dict''>", "")
    result2 = result2.replace("type='str'", "")
    result2 = result2.replace("type='list'", "")
    result2 = result2.replace("type='dict'", "")
    result2 = result2.replace("<?xml version='1.0' encoding='UTF-8' ?>", "")
    result2 = result2.replace('<root>', "")
    result2 = result2.replace('</root>', "")
    result2 = result2.replace(' >', ">")
    result2 = result2.replace('item',xmlListName )
    ListNameStart = '<' + xmlListName + '>'
    print(ListNameStart)
    replaceListBegin=ListNameStart+ListNameStart
    print(replaceListBegin)
    result2 = result2.replace(replaceListBegin, ListNameStart)

    # result2 = result2.replace(ListNameEnd, "")

    ListNameEnd = '</' + xmlListName + '>'
    replaceListEnd = ListNameEnd + ListNameEnd
    result2 = result2.replace(replaceListEnd, ListNameEnd)

# result2 = result2.replace(ListNameEnd, "")
    print("result2")
    print(result2)
    return result2


# 响应取值替换
def replaceBody(response):
    print(response)  #dict
    print("响应值")
    resHead = response['data']['resHead']
    print(resHead)
    resBody = response['data']['resBody']
    print(resBody)
    res = {"resHead": resHead, "resBody": resBody}

    return res

# 拼接xml格式
def replacePayload(result):
    # payload固定的不需要修改
    print("进入")
    payload = "<soapenv:Envelope xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:web=\"http://webservice.gzzcd.credit.lyzd.com\">\r\n    <soapenv:Header/>\r\n    <soapenv:Body>\r\n        <web:serviceAndFile>\r\n            <data>\r\n                <![CDATA[<DOCUMENT><TITLE>9111000010112001XW</TITLE><HEAD>HEADREPLACE</HEAD><BODY>BODYREPLACE</BODY></DOCUMENT>]]>\r\n\r\n            </data>\r\n            <file></file>\r\n        </web:serviceAndFile>\r\n    </soapenv:Body>\r\n</soapenv:Envelope>"
    payload = payload.replace("HEADREPLACE", result['resHead'])
    payload = payload.replace("BODYREPLACE", result['resBody'])
    print("返回值")

    return payload

# 广州解密拼接
def replaceXmlPretty(response):
    resxml = xml.dom.minidom.parseString(response)
    xml_pretty_str = resxml.toprettyxml()
    print(xml_pretty_str)
    print("FFFFFFFF")
    print(type(xml_pretty_str))

    xmlstr = str(xml_pretty_str)
    xmlstr = xmlstr.replace('<?xml version="1.0" ?>', '')
    xmlstr = xmlstr.replace("<?xml version='1.0' ?>", '')



    headstart = xmlstr.rfind("&lt;HEAD&gt;")
    headend = xmlstr.rfind("/HEAD&gt")
    substrhead = xmlstr[headstart:headend]
    substrhead = substrhead.replace("&lt;HEAD&gt;", '')
    decryptHead = substrhead.replace("&lt;", '')
    print(decryptHead)  # 截取后的head

    bodystart = xmlstr.rfind("&lt;BODY&gt;")
    bodyend = xmlstr.rfind("/BODY&gt;")
    substrbody = xmlstr[bodystart:bodyend]
    substrbody = substrbody.replace("&lt;BODY&gt;", '')
    decryptBody = substrbody.replace("&lt;", '')
    print(decryptBody)  # 截取后的body

    # 构造解密入参
    param = {}
    param['reqHead'] = decryptHead
    param['reqBody'] = decryptBody

    print("加密参数:%s"%param)
    return param




#
# if __name__ == '__main__':
#     path = "../backend/case/files/"
#     os.path.expanduser(path)
#     a = xmlDataBuild(path,341)
